package com.example.excel_util.export;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.web.servlet.view.AbstractView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 *
 */
@Slf4j
public class JxlsExcelView extends AbstractView {

    //private static final Logger logger = LoggerFactory.getLogger(JxlsExcelView.class);
    private static final String CONTENT_TYPE = "application/vnd.ms-excel";
    private static final String EXCEL_DIR = "excel";

    /**
     * 模板路径
     */
    private String templatePath;

    /**
     * 导出名称
     */
    private String exportName;


    public JxlsExcelView(String templatePath, String exportName) {
        if(!StringUtils.isEmpty(templatePath)) {
            this.templatePath = EXCEL_DIR + (templatePath.startsWith("/") ? "" : "/") + templatePath;
        } else {
            log.error("Empty excel templatePath specified for \"{}\"", exportName);
        }
        if (exportName != null) {
            try {
                exportName = URLEncoder.encode(exportName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        this.exportName = exportName;
        setContentType(CONTENT_TYPE);
    }

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
                                           HttpServletResponse response) throws Exception {
        this.exportName = this.exportName + ".xls";
        this.exportName = new String(this.exportName.getBytes(StandardCharsets.UTF_8));
        Context context = new Context(model);
        response.setContentType(getContentType());
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + this.exportName);
        ServletOutputStream os = response.getOutputStream();
        InputStream is = getClass().getClassLoader().getResourceAsStream(templatePath);
        JxlsHelper.getInstance().processTemplate(is, os, context);
        is.close();
    }




}

